import { defineStore } from 'pinia';
import messageApi from '@/api/message';
import { useUserStore } from '@/store/userStore';

export const useMessageStore = defineStore('message', {
    state: () => ({
        likeMessages: [],
        commentMessages: [],
        followMessages: [],
        activityMessages: [],
        privateSessions: [],
        currentSession: null
    }),
    actions: {
        async fetchAll() {
            const userStore = useUserStore();
            const userId = userStore.userId;

            const [likeRes, commentRes, followRes, activityRes, sessionRes] = await Promise.all([
                messageApi.getLikeMessages(userId),
                messageApi.getCommentMessages(userId),
                messageApi.getFollowMessages(userId),
                messageApi.getActivityNotifications(userId),
                messageApi.getPrivateSessions(userId)
            ]);

            this.likeMessages = likeRes.data.data;
            this.commentMessages = commentRes.data.data;
            this.followMessages = followRes.data.data;
            this.activityMessages = activityRes.data.data;
            this.privateSessions = sessionRes.data.data;
        },
        async fetchPrivateMessages(sessionId) {
            const userStore = useUserStore();
            const userId = userStore.userId;

            const res = await messageApi.getPrivateMessages(sessionId, userId, 1, 10);
            this.currentSession = {
                id: sessionId,
                messages: res.data.data
            };
        },
        async sendMessage(receiverId, content) {
            const userStore = useUserStore();
            const userId = userStore.userId;

            await messageApi.sendPrivateMessage(userId, receiverId, content);
            if (!this.currentSession) {
                this.currentSession = {
                    id: receiverId,
                    messages: []
                };
            }
            this.currentSession.messages.push({
                content,
                isSent: true,
                time: new Date()
            });
        }
    }
});
